package com.lxq.LeetCode.addBinary;

public class Solution {
    public static void main(String[] args) {
        System.out.println(addBinary("1010", "1011"));
    }

    //法一
    public static String addBinary(String a, String b) {
        return Integer.toBinaryString(
                Integer.parseInt(a, 2) + Integer.parseInt(b, 2)
        );
    }

    //法二
    public static String addBinary2(String a, String b) {
        String res = "";
        int pa = a.length() - 1;
        int pb = b.length() - 1;
        int carry = 0;
        int temp = 0;
        while (pa >= 0 && pb >= 0) {
            temp = (a.charAt(pa) - '0') + (b.charAt(pb) - '0') + carry;
            res = temp % 2 + res;
            carry = temp > 1 ? 1 : 0;
            pa--;
            pb--;
        }
        while (pa >= 0) {
            temp = (a.charAt(pa) - '0') + carry;
            res = temp % 2 + res;
            carry = temp > 1 ? 1 : 0;
            pa--;
        }
        while (pb >= 0) {
            temp = (b.charAt(pb) - '0') + carry;
            res = temp % 2 + res;
            carry = temp > 1 ? 1 : 0;
            pb--;
        }
        if (carry == 1) {
            res = "1" + res;
        }

        return res;
    }
}
